package com.csj.picture.client;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import org.springframework.http.codec.ServerSentEvent;

@Component
public class AiInterfaceClient {

    // 目标接口的基础地址（前缀）
    private static final String BASE_URL = "http://localhost:8081/api";

    // 初始化WebClient（响应式HTTP客户端）
    private final WebClient webClient;

    public AiInterfaceClient() {
        this.webClient = WebClient.builder()
                .baseUrl(BASE_URL)
                .build();
    }

    /**
     * 调用目标接口的/ai/chat接口，返回与原接口一致的响应格式
     * @param memoryId 原接口所需的memoryId参数
     * @param message 原接口所需的message参数
     * @return 与原接口相同的Flux<ServerSentEvent<String>>
     */
    public Flux<ServerSentEvent<String>> callChatInterface(int memoryId, String message) {
        return webClient.get()
                // 拼接目标接口的路径：/ai/chat
                .uri("/ai/chat?memoryId={memoryId}&message={message}", memoryId, message)
                // 声明接收SSE（Server-Sent Events）格式的响应
                .accept(MediaType.TEXT_EVENT_STREAM)
                // 发送请求并将响应体转换为Flux<ServerSentEvent<String>>
                .retrieve()
                .bodyToFlux(ServerSentEvent.class)
                // 转换类型（确保泛型正确）
                .map(event -> (ServerSentEvent<String>) event);
    }
}